import {
  reqOrderAddress,
  reqOrderInfo,
  reqOrderBuyNow,
  reqSubmitOrder,
  reqPrePayInfo
} from '../../../api/orderpay'
import Schema from 'async-validator'
import { formatTime } from '../../../utils/formatTime'
import { toast } from '@/utils/extendApi'

import { debounce } from 'miniprogram-licia'

const app = getApp()

Page({
  data: {
    buyName: '', // 订购人姓名
    buyPhone: '', // 订购人手机号
    deliveryDate: '', // 期望送达日期
    blessing: '', // 祝福语
    show: false, // 期望送达日期弹框
    minDate: new Date().getTime(),
    orderAddress: {},
    orderInfo: {}
  },
  submitOrder: debounce(async function () {
    const {
      buyName,
      buyPhone,
      deliveryDate,
      blessing,
      orderAddress,
      orderInfo
    } = this.data
    const params = {
      buyName,
      buyPhone,
      cartList: orderInfo.cartVoList,
      deliveryDate,
      remarks: blessing,
      userAddressId: orderAddress.id
    }
    const { valid } = await this.validatorPerson(params)
    if (!valid) return
    const res = await reqSubmitOrder(params)
    if (res.code === 200) {
      this.orderNo = res.data
      this.advancePay()
    }
  }, 500),
  //预支付
  async advancePay() {
    try {
      const payParams = await reqPrePayInfo(this.orderNo)
      if (payParams.code === 200) {
        const payInfo = await wx.requestPayment(payParams.data)
        console.log(payInfo)
      }
    } catch (error) {
      console.error(error)
      toast({
        title: '支付异常，请联系客服',
        icon: 'error'
      })
    }
  },
  validatorPerson(params) {
    //验证收货人，是否只包含大小写字母、数字和中文字符
    const nameRegExp = '^[a-zA-Z\\d\\u4e00-\\u9fa5]+$'
    //验证手机号，是否符合中国大陆手机号码的格式
    const phoneReg = '^1[2-9]\\d{9}$'
    const rules = {
      userAddressId: [{ required: true, message: '请选择收货地址' }],
      buyName: [
        { required: true, message: '请输入订购人姓名' },
        { pattern: nameRegExp, message: '订购人姓名不合法' }
      ],
      buyPhone: [
        { required: true, message: '请输入收货人手机号' },
        { pattern: phoneReg, message: '收货人手机号不合法' }
      ],
      deliveryDate: [{ required: true, message: '请选择期望日期' }]
    }
    const validator = new Schema(rules)

    return new Promise((resolve) => {
      validator.validate(params, (errors) => {
        if (errors) {
          toast({ title: errors[0].message })
          resolve({ valid: false })
        } else {
          resolve({ valid: true })
        }
      })
    })
  },
  onShow() {
    this.getOrderAddress()
    this.getOrderInfo()
  },
  async getOrderInfo() {
    const { goodsId, blessing } = this.data
    const { data: orderInfo } = goodsId
      ? await reqOrderBuyNow({ goodsId, blessing })
      : await reqOrderInfo()
    const orderGoods = orderInfo.cartVoList.find((item) => item.blessing !== '')
    this.setData({
      orderInfo,
      blessing: !orderGoods ? '' : orderGoods.blessing
    })
  },
  async getOrderAddress() {
    const address = app.globalData.address
    if (address.id) {
      console.log(address)
      this.setData({
        orderAddress: address
      })
      return
    }
    const { data: orderAddress } = await reqOrderAddress()
    this.setData({
      orderAddress
    })
  },
  // 选择期望送达日期
  onShowDateTimerPopUp() {
    this.setData({
      show: true
    })
  },

  // 期望送达日期确定按钮
  onConfirmTimerPicker(event) {
    const timeRes = formatTime(new Date(event.detail))
    this.setData({
      show: false,
      deliveryDate: timeRes
    })
  },

  // 期望送达日期取消按钮 以及 关闭弹框时触发
  onCancelTimePicker() {
    this.setData({
      show: false,
      minDate: new Date().getTime(),
      currentDate: new Date().getTime()
    })
  },

  // 跳转到收货地址
  toAddress() {
    wx.navigateTo({
      url: '/modules/settingModule/pages/address/list/index'
    })
  },
  onLoad(options) {
    this.setData({
      ...options
    })
  },
  onUnload() {
    app.globalData.address = {}
  }
})
